import re

# match自带开头^

ret1 = re.match("[0-9]", "765test")
print(ret1.group())                             # "7"

ret2 = re.match("嫦娥\d号","嫦娥1号发射成功")
print(ret2.group())                             # "嫦娥1号"

# 去转义
src = "c:\\a\\b\\c" 
ret3 = re.match("c:\\\\a", src)                 # "c:\a"
print(ret3.group())
ret4 = re.match(r"c:\\a", src)                  # str前加个r有去掉转义的作用, 类似c#的@"xxxxx"--->学名叫原始字符串
print(ret4.group())                             # "c:\a"

# 复数匹配
ret5 = re.match("[a-zA-Z_]+[\w_]*","_name")
print(ret5.group())                             # "_name"
ret6 = re.match("[a-zA-Z_]+[\w_]*","2_name")    # None

# 复数匹配, 指定个数
ret7 = re.match("[a-zA-Z0-9_]{6}","12a3g45678") # 匹配连续6个
print(ret7.group())                             # "12a3g4"

# 字符串结尾
ret8 = re.match("[\w]{4,20}@163\.com$", "xiaoWang@163.comheihei")   # None
ret9 = re.match("[\w]{4,20}@163\.com$", "xiaoWang@163.com")         # "xiaoWang@163.com"
print(ret9.group())

# 单词边界
ret10 = re.match(r".*\bver\b", "ho ver abc")    
print(ret10.group())                                    # "ho ver"

# 非单词边界
ret11 = re.match(r".*\Bver\B", "hoverabc")
print(ret11.group())                                    # "hover"
ret12 = re.match(r".*\Bver\B", "ho verabc")             # None

# 逻辑或: 匹配"|"左右的任意一个表达式
ret13 = re.match("[1-9]?\d$|100","78")
print(ret13.group())                                    # "78"
ret14 = re.match("[1-9]?\d$|100","100")
print(ret14.group())                                    # "100"

# ():分组, group标号从1开始, 不是从0
ret15 = re.match("([^-]*)-(\d+)","010-12345678")
print(ret15.group())                                    # "010-12345678"
print(ret15.group(1))                                   # "010"
print(ret15.group(2))                                   # "12345678"

# 分组分得的组可以用\n来引用, \1表示第一个组, \2表示第二个组
ret16 = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h1></html>")
print(ret16.group())                                    # "<html><h1>www.itcast.cn</h1></html>"

# 分组分得的组可以另取别名, 然后按名字来引用, 算是上面的增强版本, 在分组括号中加入?P<name>和?P=name进行注册和引用
ret17 = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>")
print(ret17.group())                                    # "<html><h1>www.itcast.cn</h1></html>"